<!-- 公司管理 -->
<template>
    <div >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="公司名称">
                            <a-input v-model="companyName" placeholder="请输入公司名称" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="统一社会信用代码">
                            <a-input v-model="socialCode" placeholder="请输入统一社会信用代码" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='6' :sm='24'>
                        <a-form-item label="状态">
                            <a-select v-model="state" placeholder="请选择" @change="getData">
                                <a-select-option v-for="item in statusList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='6' :sm='24'>
                        <a-form-item label="实名状态">
                            <a-select v-model="realNameStatus" placeholder="请选择" @change="getData">
                                <a-select-option v-for="item in realNameStatusList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='10' :sm='24'>
                        <a-form-item label="时间">
                            <a-range-picker @change="onDateChange" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button type='primary' @click="getData">查询</a-button>
                            <a-button style="margin-left: 20px" type='' @click="add">添加公司</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  

        <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ total: total ,showSizeChanger: true,pageSize: size,}" size="small" :scroll="{ x: 1200, }">
            <div slot="businessLicense" slot-scope="businessLicense">
                <a href="javascript:void(0)" @click="lookLicense(businessLicense)">查看</a>
            </div>
            <div slot="remark" slot-scope="remark">
                <div>{{remark == '' || remark == null ? '-' : remark}}</div>
            </div>
            <div slot="realNameStatus" slot-scope="realNameStatus">
                <div v-for="(item,i) in realNameStatusList" :key="item.id">
                    <a-tag v-if="item.id == realNameStatus" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="state" slot-scope="state">
                <a-badge :status="state | statusTypeFilter" :text="state | statusFilter" />
            </div>
            <div slot="operation" slot-scope="text,record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="detail(record)">详情</a-button>
                    <a-button v-if="record.state == 0" type="link" @click="updateState(record,1)">启用</a-button>
                    <a-button v-else type="link" @click="updateState(record,0)">停用</a-button>
                </div>
            </div>
        </a-table>

        <a-modal 
            v-model="visible" 
            title="添加公司"
            @ok="handleOk" 
            @cancel="visible = false">
            <div>
                <a-form-model :model="company" ref="ruleForm" :rules="rules" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
                    <a-form-model-item label="公司名称" prop="companyName">
                        <a-input v-model="company.companyName" allow-clear placeholder="请输入公司名称" />
                    </a-form-model-item>
                    <a-form-model-item label="统一社会信用代码" prop="socialCode">
                        <a-input v-model="company.socialCode" allow-clear placeholder="请输入统一社会信用代码" />
                    </a-form-model-item>
                    <a-form-model-item ref="file" label="营业执照" help="支持扩展名JPG/PNG格式，10M以内" prop="businessLicense">
                        <a-upload
                            name="file"
                            list-type="picture-card"
                            @change="handleChange"
                            :before-upload="beforeUpload"
                            :fileList = fileList
                            @preview="handlePreview"
                            :remove="()=>{fileList = []}"
                        >
                            <div v-if="fileList.length < 1">
                                <a-icon type="plus" />
                                <div class="ant-upload-text">
                                上传
                                </div>
                            </div>
                        </a-upload>
                    </a-form-model-item>
                    <a-form-model-item label="联系人" >
                        <a-input v-model="company.contactName" allow-clear placeholder="请输入联系人" />
                    </a-form-model-item>
                    <a-form-model-item label="联系电话" >
                        <a-input v-model="company.contactPhone" allow-clear placeholder="请输入联系电话" />
                    </a-form-model-item>
                    <a-form-model-item label="备注" >
                        <a-textarea v-model="company.remark" allow-clear placeholder="备注" :auto-size="{ minRows: 3, maxRows: 5 }" :maxLength="200"/>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>

        <!-- 预览图片 -->
        <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
            <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { getBase64 , fileProcess } from '@/utils/util';
import { queryCompanyList , createCompany , updateCompanyState } from '@/api/services/company';
import { fileUpload } from '@/api/system';
export default {
    data () {
        return {
            companyName: '', // 公司名称
            socialCode: '', // 社会统一信用代码
            startTime: '',
            endTime: '',
            columns,
            page: 1,
            size: 10,
            isload: false,
            dataList: [],
            total: 0,
            state: undefined, // 状态
            statusList: [
                { id: 0, name: '已停用'},
                { id: 1, name: '使用中'},
            ],
            realNameStatus: undefined, // 实名状态
            realNameStatusList: [
                { id: 0, name: '未认证'},
                { id: 1, name: '认证中'},
                { id: 2, name: '认证失败'},
                { id: 3, name: '已实名'},
            ],
            visible: false,
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            company: {
                id: '',
                companyName: '', // 公司名称
                businessLicense: '', // 营业执照图片URL
                socialCode: '', // 统一社会信用代码
                contactName: '', // 姓名
                contactPhone: '', // 手机号
                remark: '', // 备注
            },
            fileList: [],
            previewVisible: false,
            previewImage: '',
            rules: {
                companyName: [
                    { required: true, message: '请输入公司名称', trigger: 'blur' },
                ],
                socialCode: [{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }],
                businessLicense: [{required: true, message: '请上传营业执照', trigger: 'change'}, ] 
            },
        };
    },
    created(){
        this.getData();
    },
    methods: {
        // 日期筛选
        onDateChange(date,dateStr){
            console.log(date,dateStr)
            if(date.length > 0){
                this.startTime = date[0].format('YYYY-MM-DD')
                this.endTime = date[1].format('YYYY-MM-DD')
            }else{
                this.startTime = ''
                this.endTime = ''
            }
            this.getData()
        },
        // 获取账户列表数据
        getData(){
            let _this = this
            _this.isload = true;
            const params = {
                'startTime': _this.startTime,
                'endTime': _this.endTime,
                'companyName': _this.companyName,
                'socialCode': _this.socialCode,
                'state': _this.state,
                'realNameStatus': _this.realNameStatus,
                'pageSize': _this.size,
                'pageIndex': _this.page,
            }
            queryCompanyList(params)
            .then(res=>{
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data;
                    _this.total = res.totalCount;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 查看详情
        detail(item){
            this.$router.push({ path: '/servicesCompany/companyDetail', query: { 'companyId': item.id}})
        },
        // 上传营业执照
        beforeUpload(file) {
            return false;
        },
        handleChange({file,fileList}) {
            let _this = this
            const status = file.status;
            if(file.status === 'removed'){
                this.fileList = []
                return
            }
            this.fileList = fileList
            const formData = new FormData();
            formData.append('multipartFile',file)
            fileUpload(formData)
            .then(res=>{
                if(res.success){
                    _this.company.businessLicense = res.data
                    _this.$refs.ruleForm.clearValidate()
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        async handlePreview(file) {
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }
            this.previewImage = file.url || file.preview;
            this.previewVisible = true;
        },
        // 添加公司
        add(){
            this.visible = true
        },
        handleOk(){
            let _this = this
            _this.$refs.ruleForm.validate(valid => {
                if(valid){
                    const params = {
                        'companyName': _this.company.companyName,
                        'socialCode': _this.company.socialCode,
                        'contactName': _this.company.contactName,
                        'contactPhone': _this.company.contactPhone,
                        'businessLicense': _this.company.businessLicense,
                        'remark': _this.company.remark,
                    }
                    createCompany(params)
                    .then(res=>{
                        if(res.success){
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: '创建成功',
                                duration: 8
                            })
                            _this.visible = false;
                            _this.getData()
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        // 查看营业执照
        lookLicense(src){
            this.previewImage = src;
            this.previewVisible = true;
        },
        // 状态切换
        updateState(item,state){
            let _this = this
            _this.$confirm({
                title: '温馨提示',
                content: state == 1 ? '是否确认开启当前公司' : '是否确认关闭当前公司',
                okText: state == 1 ? '确认开启' : '确认关闭',
                onOk() {
                    const params = {
                        'companyId': item.id,
                        'state': state,
                    }
                    updateCompanyState(params)
                    .then(res=>{
                        if(res.success){
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: state == 1 ? '开启成功' : '关闭成功',
                                duration: 8
                            })
                            _this.getData()
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                },
                onCancel() {},
            });
        },
    }
}

</script>
<style scoped>

</style>